package com.dayaokeji.rhythmschoolstudent.client.common

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.View
import com.dayaokeji.imkitwrapper.fragment.AnswerChatFragment
import com.dayaokeji.rhythmschoolstudent.R
import com.dayaokeji.rhythmschoolstudent.client.common.base.ActivityTemplateMethod
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity
import com.dayaokeji.rhythmschoolstudent.receiver.VieAnswerBean
import com.dayaokeji.rhythmschoolstudent.utils.PrefUtils
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils
import com.dayaokeji.server_api.ApiUtils
import com.dayaokeji.server_api.ServerResponse
import com.dayaokeji.server_api.api.VieAnswerApi
import com.dayaokeji.server_api.domain.VieAnswer
import com.orhanobut.logger.Logger
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_vie_answer.*
import retrofit2.Call
import java.util.concurrent.TimeUnit

/**
 * 抢答
 */
class VieAnswerActivity : BaseActivity() , ActivityTemplateMethod{

    companion object {
        private const val ANSWER_FRAGMENT_FLAG = "answer_fragment_flag"
        private const val RECEIVER_BEAN = "receiver_bean"

        fun navigation(context: Context, receiverBean: VieAnswerBean) {
            val intent = Intent(context, VieAnswerActivity::class.java)
            intent.putExtra(RECEIVER_BEAN,receiverBean)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            context.startActivity(intent)
        }
    }

    private var answerFragment: AnswerChatFragment? = null
    private var vieAnswerBean: VieAnswerBean? = null
    private var uid: Long = -1
    private val vieAnswerApi by lazy { ApiUtils.getApi(VieAnswerApi::class.java) }
    private var replyCall:Call<ServerResponse<Void>>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_vie_answer)
        toolbar?.let {
            setSupportActionBar(toolbar)
        }

        init()
    }

    override fun init() {

        vieAnswerBean = intent.getSerializableExtra(RECEIVER_BEAN) as VieAnswerBean
        uid = UserUtils.getCurrentUid()
        if (vieAnswerBean == null || uid == -1L) {
            Logger.e("vieAnswerBean is null")
            return
        }
        super.init()
    }

    override fun setupView() {
        supportActionBar?.title = "与"+vieAnswerBean?.teacherName+"交互中..."
        vieAnswerBean?.let {
            if (answerFragment == null) {
                answerFragment = AnswerChatFragment.newInstance(uid,it.teacherIM)
            }
            supportFragmentManager.beginTransaction().replace(R.id.fl_content, this!!.answerFragment!!,ANSWER_FRAGMENT_FLAG).commit()
        }

        addDisposable(Observable.interval(3,TimeUnit.SECONDS).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe {
            answerFragment?.let {
                val refreshConnectState = it.refreshConnectState()
                if (refreshConnectState){
                    supportActionBar?.setSubtitle("连接正常")
                }else{
                    supportActionBar?.setSubtitle("正在连接...")
                }
            }
        })

    }

    override fun setupViewData() {
        vieAnswerBean?.let {
            if (it.isReply) {
                PrefUtils.setFirstAudio(true)
                if (PrefUtils.isFirstAudio()) {
                    answerFragment?.let {
                        it.setSendAudioCallback {
                            if (PrefUtils.isFirstAudio()) {
                                rollCall()
                            }
                            PrefUtils.setFirstAudio(false)
                        }
                    }
                }

            }
        }
    }

    /**
     * 回应点名
     */
    private fun rollCall(){
        vieAnswerBean?.let {
            val vieAnswer = VieAnswer(it.relObjectType,it.relObjectDetailID)
            replyCall = vieAnswerApi.reply(vieAnswer)
            replyCall?.enqueue(object :ServerCallback<Void>(){
                override fun onResponse(success: Boolean, response: ServerResponse<Void>?) {
                    if (success) {
                        Logger.d("回应点名成功")
                    }
                }
            })
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        replyCall?.cancel()
    }
}
